/* eslint-disable no-useless-catch */
/* eslint-disable-next-line no-case-declarations */
import { queryBusinessAppId } from '@/api/h5';
import '@/assets/fonts/iconfont.css';
import '@/assets/less/global.less';
import Layer from '@/components/Layer';
import { parseUrl } from '@/utils';
import '@vant/touch-emulator';
import { Lazyload, Toast } from 'vant';
import VConsole from 'VConsole';
import { createApp } from 'vue';
import Cropper from 'vue3-cropper';
import 'vue3-cropper/lib/vue3-cropper.css';
import App from './App.vue';
import router from './router';
import store from './store';

window.suiteid = process.env.VUE_APP_Suiteid;
window.isDeploy = /deploy/i.test(location.pathname); // 在公众号中打开的购买页面
window.isActivity = /(redEnvelope|redPackage)/i.test(location.pathname); // 在公众号中打开的活动页面
window.isAssist = /assist/i.test(location.pathname); // 在企业打开的部署页面
window.isWX = /MicroMessenger/i.test(window.navigator.userAgent) && !/wxwork/i.test(window.navigator.userAgent); // 客户端程序是微信
if (process.env.VUE_APP_VConsole === '1') {
  window.vConsole = new VConsole();
  console.log('window.suiteid', window.suiteid);
  console.log('document.body.clientWidth', document.body.clientWidth);
  console.log('document.body.clientHeight', document.body.clientHeight);
  console.log('process.env.VUE_APP_CorpId', process.env.VUE_APP_CorpId);
  console.log('window.navigator', window.navigator);
  console.log('window.location.href', window.location.href);
}
router.afterEach((to, from, next) => {
  window.scrollTo(0, 0);
});

Toast.setDefaultOptions('loading', {
  duration: 0,
  forbidClick: true,
});
// 初始化环境变量
const initEnv = (wxAuthCode, urlSearchParams) => {
  const { nickName, headimgurl, unionid, openId, accessToken } = urlSearchParams;
  const tmp = {
    nickName: nickName || '',
    headimgurl: headimgurl || '',
    unionid: unionid || '',
    openId: openId || '',
  };
  if (tmp.unionid || tmp.openId) {
    window.wxUserInfo = tmp;
    sessionStorage.setItem('wxUserInfo', JSON.stringify(tmp));
  } else {
    window.wxUserInfo = JSON.parse(sessionStorage.getItem('wxUserInfo'));
  }
  if (!window.businessId) {
    window.businessId = sessionStorage.getItem('businessId') || '';
  } else {
    sessionStorage.setItem('businessId', window.businessId);
  }
  if (!accessToken) {
    window.businessId = sessionStorage.getItem('businessId') || '';
  } else {
    sessionStorage.setItem('token', accessToken);
  }
  window.corpID = sessionStorage.getItem('corpID') || '';
  window.agentId = sessionStorage.getItem('agentId') || '';
  window.sysUserInfo = JSON.parse(sessionStorage.getItem('sysUserInfo'));
  window.businessAgentId = sessionStorage.getItem('businessAgentId') || '';
  window.sysLoginCode = Number(sessionStorage.getItem('sysLoginCode') || '');
  const wxAPP = /wxwork|MicroMessenger/i.test(window.navigator.userAgent);
  const browser = !/wxwork|MicroMessenger/i.test(window.navigator.userAgent);
  const dev = process.env.NODE_ENV === 'development';
  let runtimeEnv = 0;
  if (browser && !dev) {
    // 在浏览器中打开 非开发模式
    runtimeEnv = 0;
  }
  if (wxAPP && !window.businessAgentId) {
    // 在微信中打开 未初始化
    runtimeEnv = 1;
  }
  if (browser && dev && !window.businessAgentId) {
    // 在浏览器中打开 开发模式 未初始化
    runtimeEnv = 1;
  }
  if (wxAPP && window.businessAgentId) {
    // 在微信中打开 已初始化
    runtimeEnv = 3;
  }
  if (browser && dev && window.businessAgentId) {
    // 在浏览器中打开 开发模式 已初始化
    runtimeEnv = 3;
  }
  return runtimeEnv;
};
// 微信登录
const wechatInit = async () => {
  if (window.businessId) {
    console.log('start queryBusinessAppId');
    const res2 = await queryBusinessAppId(window.businessId);
    window.corpID = res2.data.corpId;
    window.agentId = res2.data.buinessAppAgentId;
    window.businessAgentId = res2.data.businessAgentId;
    console.log('agentId', window.agentId);
  }

  sessionStorage.setItem('corpID', window.corpID);
  sessionStorage.setItem('agentId', window.agentId);
  sessionStorage.setItem('businessAgentId', window.businessAgentId);
};
const callNext = (to, from, next) => {
  var u = navigator.userAgent;
  var isIOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); // ios终端
  let toPathShadow = `${process.env.VUE_APP_PUBLIC_PATH}${to.path.slice(1)}`; // 去掉多余的斜线 /
  let newTargetUrl = `${location.protocol}//${location.host}${process.env.VUE_APP_PUBLIC_PATH}${to.fullPath.slice(1)}`; // 去掉多余的斜线 /
  // 处理在IOS 微信客户端中非首屏页面调用wx.config失败的问题
  // if (isIOS && window.isWX && /^(DeployBuy|Activity)$/.test(to.name) && toPathShadow !== location.pathname) {
  if (isIOS && /^(DeployBuy)$/.test(to.name) && toPathShadow !== location.pathname) {
    location.assign(newTargetUrl); // 此处不可使用location.replace
  }
  next();
};
router.beforeEach((to, from, next) => {
  const urlSearchParams = parseUrl(); // url search部分参数
  window.businessId = to.params.businessId || '';
  const runtimeEnv = initEnv(urlSearchParams);
  if (/error|openInWxwork/.test(to.path) && runtimeEnv !== 3) {
    next();
    return;
  }
  console.log('runtimeEnv', runtimeEnv);
  switch (runtimeEnv) {
    case 0: // 1、在浏览器中打开（非开发模式）；2、在微信中打开 登录失败
      console.log('路由错误：', JSON.stringify(from), '即将跳转到/error');
      next('/error');
      break;
    case 1: // 在浏览器中打开 未初始化
      wechatInit()
        .then(() => {
          next(to, from, next);
        })
        .catch(() => {
          next('/error');
        });
      break;
    default:
      next(to, from, next);
  }
});

createApp(App)
  .provide('APP_NAME', process.env.VUE_APP_NAME)
  .use(router)
  .use(store)
  .use(Cropper)
  .use(Layer)
  .use(Lazyload, {
    lazyComponent: true,
  })
  .mount('#app');
